#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<vector>
using namespace std;

const int maxn = 10000 + 10;
int N, M;
vector<int> nextNodes[maxn];
int inDegree[maxn];
int visited[maxn];
int reward[maxn];

void init(){
	for(int i = 1; i <= N; i ++){
		nextNodes[i].clear();
	}
	memset(inDegree, 0, sizeof(int) * maxn);
	memset(visited, 0, sizeof(int) * maxn);
	memset(reward, 0, sizeof(int) * maxn);
}

bool dfs(int node){
	visited[node] = -1;
	reward[node] = 888;
	for(int nextIdx = 0; nextIdx < nextNodes[node].size(); nextIdx ++){
		int nextNode = nextNodes[node][nextIdx];
		if(visited[nextNode] == -1){
			return false;
		}else if(visited[nextNode] == 0){
			if(!dfs(nextNode)){
				return false;
			}else{
				if(reward[nextNode] + 1 > reward[node]){
					reward[node] = reward[nextNode] + 1;
				}	
			}
		}else{
			if(reward[nextNode] + 1 > reward[node]){
				reward[node] = reward[nextNode] + 1;
			}
		}
	}
	visited[node] = 1;
	return true;
}

int  solve(){
	for(int i = 1; i <= N; i ++){
		if(inDegree[i] == 0){
			if(!dfs(i)){
				return -1;
			}
		}
	}

	int sum = 0;
	for(int i = 1; i <= N; i ++){
		if(reward[i] == 0){
			return -1;
		}else{
			sum += reward[i];
		}
	}
	return sum;
}


int main(void){
	while(scanf("%d%d", &N, &M) == 2){
		init();
		for(int i = 0; i < M; i ++){
			int a, b;
			scanf("%d%d", &a, &b);
			nextNodes[a].push_back(b);
			inDegree[b] ++;	
		}
		printf("%d\n", solve());
	}
}
